<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="24" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
          <el-form-item label="姓名" prop="nickName">
            <el-input
              v-model="queryParams.nickName"
              placeholder="请输入姓名"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="手机号码" prop="phonenumber">
            <el-input
              v-model="queryParams.phonenumber"
              placeholder="请输入手机号码"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="用户状态"
              clearable
              style="width: 240px"
            >
              <el-option
                v-for="dict in dict.type.sys_normal_disable"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="dateRange"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="tagList">
          <el-table-column label="ID" align="center" prop="teacherId" />
          <el-table-column label="姓名" align="center" prop="sysUser.nickName" />
          <el-table-column label="头像" align="center">
            <template slot-scope="scope">
              <ImagePreview :src="scope.row.sysUser.avatar" :width="40"></ImagePreview>
            </template>
          </el-table-column>
          <el-table-column label="手机号" align="center" prop="sysUser.userName" />
          <el-table-column label="分类" align="center" prop="tagName" />
          <el-table-column label="每节价格" align="center" prop="lessonPrice" />
          <el-table-column label="状态" align="center">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.sysUser.status"
                active-value="0"
                inactive-value="1"
                v-hasPermi="['system:user:edit']"
                @change="handleStatusChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="排序" align="center" prop="sort" />
          <el-table-column label="创建时间" align="center" prop="createTime">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdateMetting(scope.row)">会议信息</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
          @pagination="getList" />
      </el-col>
    </el-row>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号" prop="sysUser.userName" >
              <el-input v-model="form.sysUser.userName" placeholder="请输入手机号" maxlength="20" :disabled="!!form.teacherId"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="教师姓名" prop="sysUser.nickName">
              <el-input v-model="form.sysUser.nickName" placeholder="请输入教师姓名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-row v-if="!form.teacherId">
              <el-col>
                <el-form-item label="密码" prop="sysUser.password">
                  <el-input v-model="form.sysUser.password" placeholder="请输入密码" :show-password="true" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col>
                <el-form-item label="教师分类" prop="tagIds">
                  <el-select clearable v-model="form.tagIds" placeholder="可多选" multiple style="width: 100%;">
                    <el-option v-for="item in teacherTagList" :key="item.tagId" :value="item.tagId"
                      :label="item.tagName"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col>
                <el-form-item label="课时每节价格" prop="lessonPrice">
                  <el-input type="number" v-model="form.lessonPrice" placeholder="请输入每节价格">
                    <template slot="append">（元）</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="12">
            <el-form-item label="教师头像" prop="sysUser.avatar">
              <ImageUpload v-model="form.sysUser.avatar" :limit="1"></ImageUpload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="排序" prop="sort">
          <el-input type="number" v-model="form.sort" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="个人介绍" prop="intro">
          <!-- <Editor v-model="form.intro" :height="250"></Editor> -->
          <el-input type="textarea" v-model="form.intro" rows="6"></el-input>
        </el-form-item>
        <el-form-item label="教师视频介绍" prop="videoUrl">
          <el-input maxlength="300" v-model="form.videoUrl" placeholder="请输入教师视频介绍" />
        </el-form-item>

        <el-form-item label="关联课表" prop="courseId">
          <el-select clearable v-model="form.courseId" placeholder="请选择关联的课表及上课时间" style="width: 100%;"
            @change="courseChange" :disabled="!!form.teacherId">
            <el-option v-for="item in courseList" :key="item.courseId" :value="item.courseId"
              :label="item.courseName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程表" v-if="form.courseId">
          <el-table :data="teacherTimeList" border max-height="500">
            <el-table-column label="时间" align="center" width="120">
              <template slot-scope="scope">
                <span>{{ scope.row.startTime + '~' + scope.row.endTime }}</span>
              </template>
            </el-table-column>
            <el-table-column :label="'星期' + item.char" class-name="week-style" align="center" v-for="(item, index) in week">
                <template slot-scope="scope">
                  <div class="day-item" @click="chooseDay(scope.row, item.number)" 
                    :class="{'active-day-item': scope.row.days.indexOf(item.number) != -1, 'gray' : scope.row.days.indexOf(item.number) == -1, 'disabled-day-item': !!form.teacherId}"
                    ></div>
                </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open2" width="600px" append-to-body>
      <el-form ref="meetingForm" :model="meetingForm" :rules="meetingRules" label-width="80px">
          <el-form-item label="会议软件" prop="meetingType" >
            <el-input v-model="meetingForm.meetingType" placeholder="请输入会议软件" maxlength="20"/>
          </el-form-item>
          <el-form-item label="会议号" prop="meetingCode" >
            <el-input v-model="meetingForm.meetingCode" placeholder="请输入会议号" maxlength="20"/>
          </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitMettingForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listTeacher, getTeacher, deleteTeacher, addTeacher, updateTeacher, updateMeeting } from "@/api/spoken/teacher";
import { listTeacherTag } from '@/api/spoken/teacherTag'
import { listCourse, getCourse } from '@/api/spoken/course'
import { changeUserStatus } from "@/api/system/user";
const week = [
  {number: '1', char: '一'}, 
  {number: '2', char: '二'}, 
  {number: '3', char: '三'}, 
  {number: '4', char: '四'}, 
  {number: '5', char: '五'}, 
  {number: '6', char: '六'}, 
  {number: '7', char: '日'}, 
];
export default {
  name: "Teacher",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      week,
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      tagList: null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        tagName: undefined,
      },
      dateRange: [],
      form: {
        sysUser: {}
      },
      teacherTagList: [],
      courseList: [],
      teacherTimeList: [],
      open2: false,
      meetingForm: {
        meetingType: '',
        meetingCode: ''
      },
      meetingRules: {
        meetingType: [
          { required: true, message: "会议类型不能为空", trigger: "blur" },
        ],
        meetingCode: [
          { required: true, message: "会议号不能为空", trigger: "blur" },
        ]
      },  
      // 表单校验
      rules: {
        'sysUser.userName': [
          { required: true, message: "手机号不能为空", trigger: "blur" },
          // {
          //   pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
          //   message: "请输入正确的手机号码",
          //   trigger: "blur"
          // }
        ],
        'sysUser.password': [
          { required: true, message: "密码不能为空", trigger: "blur" },
        ],
        'sysUser.nickName': [
          { required: true, message: "教师姓名不能为空", trigger: "blur" },
        ],
        'sysUser.avatar': [
          { required: true, message: "教师头像不能为空", trigger: "blur" },
        ],
        tagIds: [
          { required: true, message: "教师分类不能为空", trigger: "blur" },
        ],
        sort: [
          { required: true, message: "排序不能为空", trigger: "blur" },
        ],
        intro: [
          { required: true, message: "个人介绍不能为空", trigger: "blur" },
        ],
        videoUrl: [
          { required: true, message: "教师视频介绍不能为空", trigger: "blur" },
        ],
        lessonPrice: [
          { required: true, message: "课时每节价格不能为空", trigger: "blur" },
        ],
        courseId: [
          { required: true, message: "关联课表不能为空", trigger: "blur" },
        ]
      }
    };
  },
  watch: {
  },
  created() {
    this.getList();
    this.getTeacherTagList()
    this.getCourseList()
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listTeacher(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.tagList = response.rows;
        this.total = response.total;
        this.loading = false;
      }
      );
    },
    getTeacherTagList() {
      listTeacherTag({ pageNum: 1, pageSize: 999 }).then(res => {
        this.teacherTagList = res.rows
      })
    },
    getCourseList() {
      listCourse({ pageNum: 1, pageSize: 999 }).then(res => {
        this.courseList = res.rows
      })
    },
    // 选择课程表
    courseChange(e) {
      this.teacherTimeList = []
      // 查询课程表对应时间段
      getCourse(e).then(res => {
        let result = res.data.courseTime || []
        result.forEach(item => {
          this.teacherTimeList.push({
            startTime: item.startTime.substr(0, item.startTime.length - 3),
            endTime: item.endTime.substr(0, item.endTime.length - 3),
            courseId: item.courseId,  // 课程表ID
            courseTimeId: item.timeId,
            days: []
          })
        })
      })
    },
    chooseDay(e, number){
      if(this.form.teacherId){
        return
      }
      const index = e.days.indexOf(number)
      if(index == -1){
        e.days.push(number)
      }else{
        e.days.splice(index, 1)
      }
    },
    //, 取消按钮
    cancel() {
      this.open = false;
      this.open2 = false
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        sysUser: {
          userName: undefined,
          password: undefined,
          nickName: undefined,
          avatar: undefined
        },
        tagIds: undefined,
        intro: undefined,
        videoUrl: undefined,
        lessonPrice: undefined,
        courseId: undefined,
        teacherId: undefined,
        sort: 0
      };
      this.meetingForm = {
        meetingType: undefined,
        meetingCode: undefined,
        teacherId: undefined
      }
      this.teacherTimeList = []
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.title = "添加教师";
      this.open = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      getTeacher(row.teacherId).then(response => {
        response.data.tagIds = response.data.tagIds.split(',').map(Number)
        this.form = response.data;
        // 查询课程表时间段
        getCourse(this.form.courseId).then(res => {
          let result = res.data.courseTime || []
          result.forEach(item => {
            // 选中的日期进行回显
            const courseTime = this.form.teacherCourseTime.find(time => time.courseTimeId == item.timeId);
            this.teacherTimeList.push({
              startTime: item.startTime.substr(0, item.startTime.length - 3),
              endTime: item.endTime.substr(0, item.endTime.length - 3),
              courseId: item.courseId,  // 课程表ID
              courseTimeId: item.timeId,
              teacherId: this.form.teacherId,
              days: courseTime ? courseTime.days.split(',').map(String) : []
            })
          })
        })
        
        this.title = "修改教师";
        this.open = true;
      });
    },
    handleUpdateMetting(row){
      getTeacher(row.teacherId).then(response => {
        this.meetingForm = {
          meetingType: response.data.meetingType || '',
          meetingCode: response.data.meetingCode || '',
          teacherId: response.data.teacherId
        }
        this.title = '修改会议信息'
        this.open2 = true
      })
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let checkIndex = 0;
          for(var i = 0; i < this.teacherTimeList.length; i++){
            if(!this.teacherTimeList[i].days.length){
              checkIndex++;
            }
          }
          if(checkIndex === this.teacherTimeList.length){
            return this.$modal.msgError('课程表未选择时段');
          }
          if(Array.isArray(this.form.tagIds)){
            this.form.tagIds = this.form.tagIds.join(",")
          }
          this.teacherTimeList.forEach(item => {
            if(Array.isArray(item.days)){
              item.days = item.days.join(",")
            }
          })
          this.form.teacherCourseTime = this.teacherTimeList;
          if (this.form.teacherId != undefined) {
            updateTeacher(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTeacher(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    submitMettingForm(){
      this.$refs["meetingForm"].validate(valid => {
        if (valid) {
          updateMeeting(this.meetingForm).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open2 = false;
            this.getList();
          });
        }
      });
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.sysUser.status === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.sysUser.nickName + '"用户吗？').then(function() {
        return changeUserStatus(row.sysUser.userId, row.sysUser.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.sysUser.status = row.sysUser.status === "0" ? "1" : "0";
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除？').then(function () {
        return deleteTeacher(row.teacherId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    }
  }
};
</script>

<style scoped>
::v-deep .week-style {
  width: 70px;
  height: 70px;
  padding:0;
}

::v-deep .cell{
  padding:0 !important;
}

::v-deep .el-table--enable-row-hover .el-table__body tr:hover > td.el-table__cell{
  background-color: transparent;
}

.day-item{
  width: 90px;
  height: 70px;
  cursor: pointer;
}

.active-day-item{
  background: #0085FF;
}

.gray{
  background-color: #F5F5F5;
}

.disabled-day-item{
  cursor: not-allowed;
}
</style>